package cn.trdu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    /**
     * Before: 前置通知,目标执行之前需要执行的方法
     */
    @Before(value = "execution(public int " +
            "cn.trdu._07springaop.aop.CalculatorImpl.*(..))")
    public void befoerMethod(JoinPoint joinPoint) {
            /*
            1.getSignature():获取目标方法签名;
            2.getName():获取目标方法的方法名;
            3.getArgs():获取目标方法参数列表;
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs()) ;
        System.out.println("1.前置通知:" + name + "方法开始..."+args);
    }
    @After(value = "execution(public int cn.trdu._07springaop.aop.CalculatorImpl.*(..))")
    public  void  afterMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        System.out.println("2.后置通知:"+name+"方法结束");
    }

    @AfterReturning(value = "execution" +
            "(public int cn.trdu._07springaop.aop.CalculatorImpl.*(..))",returning = "result")
    public void  afterReturningMeTHod(JoinPoint joinPoint,Object result){
        String name=joinPoint.getSignature().getName();
        System.out.println("3.放回通知:"+name+"正常结束,结果为"+result);
    }
    @AfterThrowing(value = "execution" +
            "(public int cn.trdu._07springaop.aop.CalculatorImpl.*(..))",throwing = "ex")
    public void  afterTheowingMethod(JoinPoint joinPoint,Throwable ex){
        System.out.println("异常通知:目标方法抛出异常,异常信息为:"+ex.getMessage());

    }
    @Around(value = "execution(public int cn.trdu._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        Object result=null;
        try {
            System.out.println("111.前置通知");
            result = joinPoint.proceed();
            System.out.println("222,返回通知");
        } catch (Throwable throwable) {
            System.out.println("333.异常通知");
        } finally {
            System.out.println("444.后置通知");

        }


        return  result;
    }
}
